package com.bowen.demo.demo003.job;

import com.alibaba.fastjson.JSON;
import com.bowen.demo.demo003.request.FrontEndLogName;
import com.bowen.demo.demo003.service.MailService;
import com.bowen.demo.demo003.utils.DateUtils;
import com.bowen.demo.demo003.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * CBS前置机状态job
 * 公众号【猿码天地】
 */
@Slf4j
@Component
public class CbsFrontEndStatusJob {

	// 服务器日志目录
	@Value("${cbs.frontEnd.logPath:D:/project-prod/monitor/logs/}")
	private  String cbsFrontEndLogPath;

	// 服务器请求URL
	@Value("${cbs.frontEnd.server.address:http://127.0.0.1:8081/monitor/frontend/log}")
	private  String cbsFrontEndServerAddress;

	@Autowired
	private MailService mailService;

	// TODO 可加自动定时任务
	public void test() {
		log.info("[CBS前置机状态] job start..");
		String logFile = null;
		List<String> datas = new ArrayList<>();
		// 日志类型 从枚举通过code获取
		String[] logTypes = {"1", "2"};
		for (int i = 0; i < logTypes.length; i++) {
			String logType = logTypes[i];
			FrontEndLogName frontEndLogName = FrontEndLogName.getByCode(logType);
			try {
				if (null != frontEndLogName) {
					logFile = frontEndLogName.getName() + "_" + DateUtils.format(new Date(), "yyyyMMdd") + ".log";
				}
				List<String> result = new ArrayList<>();
				Map<String, String> param = new HashMap<>();
				param.put("logFile", cbsFrontEndLogPath + logFile);
				String cbsFrontEndLogs = HttpClientUtils.doPostJson(cbsFrontEndServerAddress, JSON.toJSONString(param));
				log.debug("CBS前置机日志读取返回：{}",cbsFrontEndLogs);
				if (StringUtils.isNotBlank(cbsFrontEndLogs)) {
					result = JSON.parseObject(cbsFrontEndLogs, List.class);
				}else{
					log.error("CBS前置机日志读取返回空，logType：{}",logType);
					String errorDate = DateUtils.format(new Date(), "yyyyMMdd HH:mm:ss");
					result.add("["+errorDate+"][ERROR]"+("1".equals(logType)?"委托支付":"代发代扣明细")+"没有生成日志!");
				}
				for (String log: result) {
					if(log.indexOf("[ERROR]") > 0){
						datas.add(log);
					}
				}
			}catch (Exception e){
				log.error("CBS前置机日志读取异常， frontEndLogName：{}", JSON.toJSONString(frontEndLogName), e);
			}
		}

		//发送邮件
		if(datas.size() > 0) {
			StringBuilder content = new StringBuilder();
			for(String log :datas) {
				content.append("\t\t").append(log).append("\n");
			}
			mailService.sendSimpleMail("zhang.bowen@belle.com.cn","前置机服务器邮件告警通知",content.toString());
		}
		log.info("[CBS前置机状态] job end..");
	}

}